package com.foreverwin.quartz.util;

import com.foreverwin.quartz.constant.ScheduleConstants;
import com.foreverwin.quartz.domain.SysJob;
import com.foreverwin.quartz.domain.SysJobLog;
import com.foreverwin.quartz.service.ISysJobLogService;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.quartz.QuartzJobBean;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * 定时任务处理
 *
 * @author ruoyi
 *
 */
public class ScheduleJob extends QuartzJobBean
{
    private static final Logger log = LoggerFactory.getLogger(ScheduleJob.class);

    private ExecutorService service = Executors.newSingleThreadExecutor();

    private final static ISysJobLogService jobLogService = (ISysJobLogService) SpringContextUtil.getBean("sysJobLogServiceImpl");

    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException
    {
        SysJob job = new SysJob();
        BeanUtils.copyBeanProp(job, context.getMergedJobDataMap().get(ScheduleConstants.TASK_PROPERTIES));

        Date startDate = new Date();
        SysJobLog jobLog = new SysJobLog();
        jobLog.setHandle( job.getHandle() + "," + DateFormatUtils.format( startDate, "yyyy-MM-dd HH:mm:ss.SSS" ) );
        jobLog.setJobBo(job.getHandle());
        jobLog.setJobName(job.getJobName());
        jobLog.setJobDesc(job.getJobDesc());
        jobLog.setJobGroup(job.getJobGroup());
        jobLog.setMethodName(job.getMethodName());
        jobLog.setMethodParam(job.getMethodParam());
        jobLog.setStartDateTime(startDate);

        long startTime = System.currentTimeMillis();

        try
        {
            // 执行任务
            log.info("任务开始执行 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
            ScheduleRunnable task = new ScheduleRunnable(job.getJobName(), job.getMethodName(), job.getMethodParam());
            Future<?> future = service.submit(task);
            future.get();
            long times = System.currentTimeMillis() - startTime;
            // 任务状态 0：成功 1：失败
            jobLog.setStatus(ScheduleConstants.SUCCESS);
            jobLog.setRunTime( times );
            jobLog.setEndDateTime( new Date() );

            log.info("任务执行结束 - 名称：{} 耗时：{} 毫秒", job.getJobName(), times);
        }
        catch (Exception e)
        {
            log.info("任务执行失败 - 名称：{} 方法：{}", job.getJobName(), job.getMethodName());
            log.error("任务执行异常  - ：", e);
            long times = System.currentTimeMillis() - startTime;
            // 任务状态 0：成功 1：失败
            jobLog.setStatus(ScheduleConstants.FAIL);
            jobLog.setExceptionInfo( e.toString().length() > 2000 ? e.toString().substring( 0, 2000 ) : e.toString() );
            jobLog.setRunTime( times );
            jobLog.setEndDateTime( new Date() );
        }
        finally
        {
            jobLogService.insertSysJobLog(jobLog);
        }
    }
}
